<template>
  <view :class="['job-list-page', currentTheme]" @scroll="onScroll"
    style="height: 100vh; overflow-y: auto; padding-bottom: 140rpx;">
    <custom-tab-bar />

    <!-- 发布新职位按钮 -->
    <view class="publish-button-container">
      <button class="publish-button" @click="goToPublishJob">发布新职位</button>
    </view>

    <!-- 移除重复的职位列表代码 -->
    <JobList :job-list="jobList" :loading-more="loadingMore" :no-more="noMore" :show-delete="true"
      @goToJobDetail="goToJobDetail" @deleteJob="deleteJob" />
    <!-- 空状态（无数据时） -->
    <view v-if="!isLoading && !errorMsg && jobList.length === 0" class="empty-container">
      <uni-icons type="info" size="48" color="#b6ccd8"></uni-icons>
      <text class="empty-text">暂无相关职位</text>
    </view>
  </view>
</template>

<script>
import { getJobPosting, deletejobPostings } from '@/api/job.js';
import JobList from '@/components/JobList.vue';
import JobHeader from '@/components/search.vue';

export default {
  components: {
    JobList,
    JobHeader
  },
  data() {
    return {
      // 主题相关
      currentTheme: 'theme1', // 当前主题，默认为主题1

      pageSize: 10,
      pageNum: 1,
      jobList: [],
      total: 0, // 总记录数
      isLoading: false,
      loadingMore: false,
      noMore: false,
      errorMsg: '',
      searchValue: '',
      city: '选择城市', // 默认城市
      currentTab: 0, // 当前选中的标签索引
    };
  },

  methods: {
    // 添加滚动事件处理
    onScroll(e) {
      // 防抖处理，避免频繁触发
      clearTimeout(this.scrollTimer);
      this.scrollTimer = setTimeout(() => {
        const scrollTop = e.detail.scrollTop;
        const scrollHeight = e.detail.scrollHeight;
        const clientHeight = e.detail.clientHeight;

        // 当滚动到底部时加载更多
        if (scrollTop + clientHeight >= scrollHeight - 20 && !this.loadingMore && !this.noMore) {
          this.pageNum++;
          this.fetchJobs(true);
        }
      }, 200);
    },

    // 修改 fetchJobs 方法，确保正确判断是否还有更多数据
    async fetchJobs(isLoadMore = false) {
      if (this.loadingMore || (isLoadMore && this.noMore)) {
        console.log('阻止重复加载或已无更多数据');
        return;
      }

      this.loadingMore = isLoadMore;
      this.isLoading = !isLoadMore;
      this.errorMsg = '';

      try {
        let res;
        const hasCity = this.city !== '选择城市';
        const hasKeyword = this.searchValue.trim() !== '';
        // 当城市为默认值时，传递空字符串
        const cityParam = hasCity ? this.city : '';
        // 添加时间戳避免缓存
        const timestamp = new Date().getTime();

        // 确保参数顺序与API定义一致
        res = await getJobPosting(this.pageNum, this.pageSize, this.searchValue, cityParam, timestamp);

        const data = res.data || {};
        const currentPageData = data.list || [];
        this.total = data.total || 0;

        if (isLoadMore) {
          this.jobList = [...this.jobList, ...currentPageData];
        } else {
          this.jobList = currentPageData;
        }

        // 修复判断逻辑：当已加载数据数量大于等于总数量时，才设置 noMore 为 true
        this.noMore = this.jobList.length >= this.total;

        // 如果返回的数据少于 pageSize，也说明没有更多数据了
        if (currentPageData.length < this.pageSize) {
          this.noMore = true;
        }
      } catch (error) {
        console.error('加载职位失败：', error);
        this.errorMsg = '加载失败，请检查网络后重试';
        if (isLoadMore) this.pageNum -= 1;
      } finally {
        this.isLoading = false;
        this.loadingMore = false;
      }
    },

    // 删除帖子
    async deleteJob(id) {
      const res = await deletejobPostings(id);
      if (res.code === 200) {
        uni.showToast({
          title: "删除成功",
          icon: "success",
          duration: 2000
        });
        this.fetchJobs();
      } else {
        uni.showToast({
          title: "删除失败，请检查网络问题，稍后重试",
          icon: "none",
          duration: 2000
        });
      }
    },

    // 修复handleSearch方法，接收搜索关键词参数
    handleSearch(keyword) {
      console.log('搜索关键词：', keyword);
      this.searchValue = keyword; // 保存搜索关键词
      this.pageNum = 1;
      this.noMore = false;
      this.fetchJobs();
    },

    goToJobDetail(id) {
      uni.navigateTo({ url: `/employPages/jobRecommendation/jobDetail/jobDetail?id=${id}` });
    },

    // 新增方法：跳转到发布职位页面
    goToPublishJob() {
      // 这里需要根据实际的页面路径进行调整
      uni.navigateTo({ url: '/employPages/jobRecommendation/pushNewJob/pushNewJob' });
    },

    goToProvinceList() {
      // 跳转到城市列表页，传递type参数
      uni.navigateTo({
        url: `/pages/job/provinceList/provinceList?type=job`
      });
    },

    reload() {
      console.log('重新加载数据');
      this.pageNum = 1;
      this.noMore = false;
      this.fetchJobs();
    },

    // 处理城市变化
    handleCityChanged(city) {
      this.city = city;
      this.reload();
    },
    // 处理城市重置
    handleCityReset() {
      this.city = '选择城市';
      this.reload();
    },
    // 重命名原 onTabChange 为 handleTabChange
    handleTabChange(index) {
      console.log('切换到标签：', index);
      this.currentTab = index;
      this.pageNum = 1;
      this.noMore = false;
      this.fetchJobs();
    },

    // 主题切换事件处理
    handleThemeChange(newTheme) {
      // 使用nextTick确保DOM更新完成后再设置主题
      this.$nextTick(() => {
        this.currentTheme = newTheme;
      });
    },

    // 其他方法保持不变
    // onTabChange(index) {
    //   console.log('切换到标签：', index);
    //   this.currentTab = index;
    //   this.pageNum = 1;
    //   this.noMore = false;
    //   this.fetchJobs();
    // }
  },

  onLoad() {
    console.log('页面加载，开始首次加载数据');
    // 加载保存的主题设置
    const savedTheme = uni.getStorageSync('currentTheme');
    if (savedTheme) {
      this.currentTheme = savedTheme;
    }

    // 初始化滚动定时器
    this.scrollTimer = null;
    this.fetchJobs();
  },

  onShow() {
    // 每次进入页面时重新加载主题设置
    const savedTheme = uni.getStorageSync('currentTheme');
    if (savedTheme && savedTheme !== this.currentTheme) {
      this.currentTheme = savedTheme;
    }

    // 每次进入页面时重新加载数据
    this.fetchJobs();
  },

  // 删除以下全局事件监听代码
  mounted() {
    // 监听全局事件
    // uni.$on('job-city-selected', (city) => {
    //   this.city = city;
    //   this.reload();
    // });

    // uni.$on('job-city-reset', () => {
    //   this.city = '选择城市';
    //   this.reload();
    // });
  },

  beforeDestroy() {
    // 移除全局事件监听
    // uni.$off('job-city-selected');
    // uni.$off('job-city-reset');
  }
};
</script>

<style scoped>
/* 强制禁用所有动画和过渡效果 */
.job-list-page * {
  transition: none !important;
  animation: none !important;
  transform: none !important;
}

.job-list-page {
  transition: none !important;
  animation: none !important;
}

/* 主题1样式 */
.job-list-page.theme1 {
  background-color: #fffefb;
  /* 大背景 */
  min-height: 100vh;
}

.job-list-page.theme1 .publish-button-container {
  padding: 10px 15px;
  background-color: #f5f4f1;
  /* 次背景 */
}

.job-list-page.theme1 .publish-button {
  width: 100%;
  background-color: #007aff;
  color: white;
  border: none;
  padding: 12px;
  border-radius: 6px;
  font-size: 16px;
  font-weight: bold;
}

.job-list-page.theme1 .search-container {
  padding: 10px 15px;
  background-color: #f5f4f1;
  /* 次背景 */
}

.job-list-page.theme1 .search-bar {
  display: flex;
  align-items: center;
  height: 40px;
  padding: 0 15px;
  background-color: #d4eaf7;
  /* 第三色 */
  border-radius: 20px;
}

/* 主题2样式 */
.job-list-page.theme2 {
  background-color: #F5EFE8;
  /* 大背景 */
  min-height: 100vh;
}

.job-list-page.theme2 .publish-button-container {
  padding: 10px 15px;
  background-color: #EEE3D7;
  /* 次背景 */
}

.job-list-page.theme2 .publish-button {
  width: 100%;
  background-color: #8b7355;
  color: white;
  border: none;
  padding: 12px;
  border-radius: 6px;
  font-size: 16px;
  font-weight: bold;
}

.job-list-page.theme2 .search-container {
  padding: 10px 15px;
  background-color: #EEE3D7;
  /* 次背景 */
}

.job-list-page.theme2 .search-bar {
  display: flex;
  align-items: center;
  height: 40px;
  padding: 0 15px;
  background-color: #BFAE9F;
  /* 第三色 */
  border-radius: 20px;
}

/* 通用样式保持不变 */
.job-list-page {
  background-color: #f8f8f8;
  min-height: 100vh;
}

/* 发布按钮样式 */
.publish-button-container {
  padding: 10px 15px;
  background-color: white;
}

.publish-button {
  width: 100%;
  background-color: #007aff;
  color: white;
  border: none;
  padding: 12px;
  border-radius: 6px;
  font-size: 16px;
  font-weight: bold;
}

/* 搜索区域样式 */
.search-container {
  padding: 10px 15px;
  background-color: white;
}

.search-bar {
  display: flex;
  align-items: center;
  height: 40px;
  padding: 0 15px;
  background-color: #f5f5f5;
  border-radius: 20px;
}

.search-input {
  flex: 1;
  height: 100%;
  font-size: 14px;
  margin-left: 8px;
  background: transparent;
}

/* 自定义导航栏样式 */
.nav-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  background-color: #ffffff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  border-bottom: 1px solid #eaeaea;
  margin-bottom: 20rpx;
}

.tab-item {
  padding: 10px 20px;
  /* 增加左右内边距，使标签更宽 */
  font-size: 16px;
  /* 调整字体大小 */
  cursor: pointer;
  transition: color 0.3s;
  color: #888;
  /* 未选中状态的颜色 */
}

.tab-item.active {
  color: #000;
  /* 选中状态的颜色 */
}

.location-container {
  display: flex;
  align-items: center;
}

.location {
  font-size: 16px;
  color: #333;
  padding: 5px 0;
  cursor: pointer;
  background-color: #f5f5f5;
  border-radius: 4px;
  display: inline-block;
  padding: 5px 10px;
}

/* 加载状态样式 */
.loading {
  text-align: center;
  padding: 30px 0;
  color: #666;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

/* 错误状态样式 */
.error-state {
  text-align: center;
  padding: 30px 0;
  color: #f53f3f;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
}

.error-state button {
  background-color: #007aff;
  color: white;
  padding: 8px 20px;
  border-radius: 4px;
  font-size: 14px;
}

/* 职位列表样式 */
.job-items {
  padding: 0 10px;
  /* 确保列表高度足够触发滚动 */
  min-height: calc(100vh - 100px);
}

.job-item {
  padding: 15px;
  background-color: white;
  border-radius: 8px;
  margin-bottom: 10px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.job-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.job-name {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  max-width: 70%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.salary {
  color: #409eff;
  font-size: 16px;
  font-weight: bold;
}

.company-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  color: #666;
  font-size: 14px;
  gap: 10px;
}

.company-info text:first-child {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.tags {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 10px;
  gap: 8px;
}

.tag {
  padding: 2px 8px;
  background-color: #f5f5f5;
  border-radius: 4px;
  font-size: 12px;
  color: #666;
}

.contact {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #999;
  font-size: 12px;
}

.contact-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.hr-avatar {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  background-color: #eee;
}

/* 加载更多提示 */
.load-more {
  text-align: center;
  padding: 15px 0;
  color: #999;
  font-size: 14px;
}

/* 空状态样式 */
.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 80px 0;
  color: #999;
}

.empty-text {
  margin-top: 15px;
  font-size: 16px;
}

/* 修改滚动容器样式 */
.job-list-page {
  height: 100vh;
  overflow-y: auto;
  padding-bottom: 80rpx;
  /* 添加底部间距，避免被导航栏遮挡 */
}
</style>